package com.megalith.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.megalith.service.MessageService;
import com.sun.deploy.association.utility.AppConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author lifp
 * @date 2023/06/29
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private RedisTemplate redisTemplate;

    String REDIS_SMS_USER_PREFIX = "sms:user:code";
    String REDIS_SMS_USER_COUNT_PREFIX = "sms:user:code:count";
    //3分钟
    long REDIS_SMS_USER_EXPIRE = 60*3;
    //次数限制
    long REDIS_SMS_USER_LIMIT = 5;


    @Override
    public String sendMessage(String userId, String phoneNumber) {


        log.info("用户:{}发送短信验证码，手机号:{}",userId,phoneNumber);

        //设置key 自动 +1
        long count=redisTemplate.boundValueOps(REDIS_SMS_USER_COUNT_PREFIX+phoneNumber).increment(1);

        if(count==1){
            //设置 过期时间
            redisTemplate.expire(REDIS_SMS_USER_COUNT_PREFIX+phoneNumber, REDIS_SMS_USER_EXPIRE , TimeUnit.SECONDS);
        }
        if(count > REDIS_SMS_USER_LIMIT){
            log.error("验证码发送频繁,超过了限定的次数");

            Long expire = redisTemplate.getExpire(REDIS_SMS_USER_COUNT_PREFIX + phoneNumber);
            return getLimitedMsg(expire);
        }
        //生成随机验证码
        String code = RandomUtil.randomNumbers(4);

        //模拟发送短信
        log.info("开始发送短信，验证码为：{}",code);

        //注意：发送失败，次数减回来 -1 表示
        //redisTemplate.boundValueOps(REDIS_SMS_USER_COUNT_PREFIX+phoneNumber).increment(-1);

        log.info("短信发送成功(*￣︶￣)，验证码为：{}",code);
        //发送成功，放入redis
        redisTemplate.opsForValue().set(REDIS_SMS_USER_PREFIX+phoneNumber, code ,REDIS_SMS_USER_EXPIRE,TimeUnit.SECONDS);

        return "验证码发送成功";
    }

    private String getLimitedMsg(Long expire){
        String msg;
        if(expire > 60){
            long min = expire / 60;
            long sec = expire % 60;
            msg = "验证码发送频繁，请"+min+"分"+sec+"秒后再试";
        }else {
            msg = "验证码发送频繁，请"+expire+"秒后再试";
        }
        return msg;
    }

    @Override
    public String checkSmsCode(String phone, String code) {
        log.info("开始验证手机号验证码:"+phone+","+code);
        String rediscode = (String) redisTemplate.opsForValue().get(REDIS_SMS_USER_PREFIX+phone);

        if (rediscode ==null || !rediscode.equals(code)){
            return "验证码错误";
        }
        //验证码使用一次后删除
        redisTemplate.delete(REDIS_SMS_USER_PREFIX+phone);
        return "验证码验证成功";
    }
}
